<template>
  <a-card :bordered="false">
    <a-spin :spinning="spinning != 0">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('m.bpm.entity.processDefName')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
                <a-input placeholder="" v-model="queryParam.processDefName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('m.bpm.entity.taskName')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
                <a-input placeholder="" v-model="queryParam.taskName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item :label="$t('m.bpm.entity.taskTitle')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
                <a-input placeholder="" v-model="queryParam.taskTitle"></a-input>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus">
              <a-col :md="6" :sm="8">
                <a-form-item :label="$t('m.bpm.entity.taskType')" :label-col="colLayout2.labelCol" :wrapper-col="colLayout2.wrapperCol">
                  <a-select v-model="queryParam.taskType" placeholder="">
                    <a-select-option value="all">{{this.$t('m.common.label.all')}}</a-select-option>
                    <a-select-option value="1">{{$t('m.bpm.other.option_todo')}}</a-select-option>
                    <a-select-option value="2">{{$t('m.bpm.other.option_pass')}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('m.common.button.query') }}</a-button>
              <a-button type="default" @click="searchReset" icon="reload" style="margin-left: 8px">{{ $t('m.common.button.reset') }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? this.$t('m.common.button.fold') : this.$t('m.common.button.expand') }}
                <ych-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
            </a-col>

          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->


      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button @click="batchSubmit" type="primary" icon="edit"> {{$t('m.bpm.other.batchDeal')}}</a-button>
        <a-button @click="batchFinishPassRound" type="primary" icon="read"> {{$t('m.bpm.other.batchPass')}}</a-button>
      </div>
      <!-- table区域-begin -->
      <div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange">
          <template slot="serialNum" slot-scope="text,record,index">
            {{(ipagination.current-1) * ipagination.pageSize + parseInt(index) + 1}}
          </template>
          <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">{{ $t('m.common.button.open') }}</a>
        </span>

        </a-table>
      </div>
    </a-spin>
    <redirect-modal ref="flowForm" @refreshParent="modalFormOk"></redirect-modal>
    <!--流程选人对话框-->
    <bpm-select-user-dialog ref="bpmSelectUserDialog" @selectUserBack="selectUserBack"></bpm-select-user-dialog>
    <!--办理分支选择对话框-->
    <bpm-button-common-dialog ref="transitionDialog" :title="$t('m.bpm.verify.tip_select_transition')" :dataVoList="transitionList"
                              @selectOk="doSubmit"></bpm-button-common-dialog>
  </a-card>
</template>

<script>

  import {postAction, putAction, getAction} from '@/api/manage'
  import {YcListMixin} from '@/mixins/YcListMixin'
  import {GardLayoutMixin} from '@/mixins/GardLayoutMixin'
  import RedirectModal from './redirect/RedirectModal'
  import YchConstant from '@/api/YchConstant'
  import BpmSelectUserDialog from '@/views/bpm/modules/bpmButton/BpmSelectUserDialog'
  import BpmButtonCommonDialog from '@/views/bpm/modules/bpmButton/BpmButtonCommonDialog'

  export default {
    name: 'TaskList',
    mixins: [YcListMixin,GardLayoutMixin],
    components: {
      RedirectModal,
      BpmSelectUserDialog,
      BpmButtonCommonDialog,
    },
    data() {
      return {
        spinning: 0,
        transitionList: [],//办理分支选择
        currentUrl: null,//记录当前动作需要调用的url，回调使用
        submitButton: {},
        finishPassRoundButton: {},
        // 表头
        columns: [
          {
            title:this.$t('m.common.label.number'),
            dataIndex: '',
            key: 'rowIndex',
            width: '50px',
            align: 'center',
            scopedSlots: { customRender: 'serialNum' },
          },
          {
            title: this.$t('m.bpm.entity.taskTitle'),
            align: 'left',
            dataIndex: 'taskTitle',
            ellipsis: true,
          },
          {
            title: this.$t('m.bpm.entity.processDefName'),
            align: 'left',
            width: '150px',
            dataIndex: 'processDefName',
            ellipsis: true,
          },
          {
            title: this.$t('m.bpm.entity.taskName'),
            align: 'left',
            width: '120px',
            dataIndex: 'taskName',
            ellipsis: true,
          },
          /*{
            title: '优先级',
            align: "center",
            dataIndex: 'priority',
            width: 80
          },*/
          {
            title: this.$t('m.bpm.entity.taskType'),
            align: 'center',
            dataIndex: 'identityString',
            width: '90px'
          },
          {
            title: this.$t('m.bpm.entity.fromUserName'),
            align: 'center',
            dataIndex: 'fromUserName',
            width: '150px',
            customRender: function (t, r, index) {
              return t + (r.fromDeptName ? '/' + r.fromDeptName : '')
            }
          },
          {
            title: this.$t('m.bpm.entity.sendTimeString'),
            align: 'center',
            dataIndex: 'sendTimeString',
            width: '130px'
          },
          {
            title: this.$t('m.bpm.entity.dueDateString'),
            align: 'center',
            dataIndex: 'dueDateString',
            width: '130px'
          },
          {
            title: this.$t('m.common.label.operate'),
            dataIndex: 'action',
            align: 'center',
            scopedSlots: {customRender: 'action'},
            width: '90px'
          }
        ],
        url: {
          list: YchConstant.PREFIX_BPM + '/bpm-front/taskRest/list/v1',
          getBpmOperateVo: YchConstant.PREFIX_BPM + '/bpm-front/displayRest/getBpmOperateVo/v1',
          getDealData: YchConstant.PREFIX_BPM + '/bpm-front/displayRest/getDealData/v1',
          validBatchCondition: YchConstant.PREFIX_BPM + '/bpm-front/displayRest/validBatchCondition/v1',
          batchSubmit: YchConstant.PREFIX_BPM + '/bpm-front/operateRest/batchSubmit/v1',
          batchFinishPassRound: YchConstant.PREFIX_BPM + '/bpm-front/operateRest/batchFinishPassRound/v1'
        }
      }
    },
    inject: ['addRouter'],
    methods: {
      handleDetail(record) {
        if (record.pcUrl.startsWith("router:")) {
          let url = record.pcUrl.substr("router:".length);
          if(url.indexOf("?") === -1){
            url += "?taskId=" + record.id + "&finish=0"
          } else {
            url += "&taskId=" + record.id + "&finish=0"
          }
          this.$router.push(url).catch(err => {})
          return
        } else if (record.pcUrl.startsWith("http:") || record.pcUrl.startsWith("https:")) {
          // http 开头的链接，暂时以新页签形式打开
          let url = record.pcUrl;
          if (url.indexOf("?") === -1) {
            url += "?taskId=" + record.id + "&finish=0"
          } else {
            url += "&taskId=" + record.id + "&finish=0"
          }
          window.open(url)
          return
        }
        let router = null
        if (this.$store.getters.formOpenType === '2') {
          router = this.addRouter({
            path: '/bpm/detailFromTask/' + record.id,
            component: resolve => require(['@/views/bpm/redirect/RedirectTab.vue'], resolve),
            props: {
              id: record.id,
              func: 'detailFromTask',
            },
            meta: {
              title: this.$t('m.bpm.common.bpmDetail'),
            }
          });
          if (router) {
            this.$router.push(router).catch(err => {})
          }
        }
        if (!router) {
          this.$refs.flowForm.detailFromTask(record.id)
        }
      },
      validOperateVo(taskId, type) {
        return new Promise((resovle) => {
          this.spinning++
          getAction(this.url.getBpmOperateVo, {id: taskId, idType: 'taskId'}).then((res) => {
            if (res.success) {
              const buttonDatas = res.result
              if (buttonDatas.open) {
                const button = buttonDatas.buttonVoList.find(vo => vo.type == type)
                if (button) {
                  resovle(button)
                } else {
                  this.messageUtil.warning(this.$t('m.bpm.verify.mei-you-quan-xian'))
                }
              } else {
                this.messageUtil.warning(this.$t('m.bpm.verify.mei-you-quan-xian'))
              }
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
            this.spinning--
          })
        })
      },
      batchSubmit() {
        if (this.selectedRowKeys.length <= 0) {
          this.messageUtil.warningWithBut(this.$t('m.bpm.verify.tip_batchDeal1'))
          return
        }

        //判断选择的是不是待办
        //判断选择的记录是不是同一个流程模板下的同一个节点
        const firstRow = this.selectionRows[0]
        for (let i = 0; i < this.selectionRows.length; i++) {
          const rowData = this.selectionRows[i]
          if (rowData.passRound == true) {
            this.messageUtil.warningWithBut(this.$t('m.bpm.verify.tip_batchDeal2'))
            return
          } else if (firstRow.processDefinitionId != rowData.processDefinitionId || firstRow.taskName != rowData.taskName) {
            this.messageUtil.warningWithBut(this.$t('m.bpm.verify.tip_batchDeal3'))
            return
          }
        }
        this.spinning++
        postAction(this.url.validBatchCondition, {taskIds: this.selectedRowKeys}).then((res) => {
          if (res.success) {
            const count = res.result.length
            if (count == this.selectedRowKeys.length) {
              this.submit()
            } else {
              this.messageUtil.warningWithBut(this.$t('m.bpm.verify.tip_batchDeal4',[count]))
              this.selectedRowKeys = res.result
              this.selectionRows = this.selectionRows.filter(vo => this.selectedRowKeys.indexOf(vo.id) != -1)
            }
          } else {
            this.messageUtil.warning(res.message)
          }
        }).finally(() => {
          this.spinning--
        });
      },
      /*办理*/
      submit() {
        const firstTaskId = this.selectedRowKeys[0]
        this.validOperateVo(firstTaskId, 'submit').then(button => {
          if (!button) {
            return
          }
          this.spinning++
          this.submitButton = button
          getAction(this.url.getDealData, {taskId: firstTaskId}).then((res) => {
            if (res.success) {
              if (res.result.last) {
                if (res.result.transitionList.length == 0) {
                  this.messageUtil.warning(this.$t('m.bpm.verify.tip_no_transition'))
                } else if (res.result.transitionList.length == 1) {
                  /*只有一个流转方向时，默认使用*/
                  this.doSubmit(res.result.transitionList[0])
                } else {
                  this.transitionList = res.result.transitionList
                  this.transitionList.forEach(vo => {
                    vo.text = vo.name
                  })
                  this.$refs.transitionDialog.visible = true
                }
              } else {
                /*不是当前节点的最后一个任务，则只需要填写意见*/
                this.doSubmit()
              }
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
            this.spinning--
          })
        })
      },
      /*实际办理或选择流转目标后的回调*/
      doSubmit(transition) {
        this.currentUrl = this.url.batchSubmit
        if (transition) {
          this.$refs.bpmSelectUserDialog.openForSubmit(this.submitButton, transition)
        } else {
          this.$refs.bpmSelectUserDialog.openNoUser(this.submitButton)
        }
      },
      batchFinishPassRound() {
        if (this.selectedRowKeys.length <= 0) {
          this.messageUtil.warningWithBut(this.$t('m.bpm.verify.tip_batchPass1'))
          return
        }
        //判断选择的是不是待阅
        for (let i = 0; i < this.selectionRows.length; i++) {
          if (this.selectionRows[i].passRound == false) {
            this.messageUtil.warningWithBut(this.$t('m.bpm.verify.tip_batchPass2'))
            return
          }
        }

        this.validOperateVo(firstTaskId, 'finishPassRound').then(button => {
          if (!button) {
            return
          }
          this.finishPassRoundButton = button
          this.finishPassRound()
        })
      },
      /*填写传阅意见*/
      finishPassRound() {
        this.currentUrl = this.url.batchFinishPassRound
        this.$refs.bpmSelectUserDialog.openNoUser(this.finishPassRoundButton)
      },
      /*流程选人框的回调，执行按钮实际动作*/
      selectUserBack(data) {
        this.spinning++
        data.taskIds = this.selectedRowKeys
        putAction(this.currentUrl, data).then((res) => {
          if (res.success) {
            if (res.code === 201) {
              let {message, result: {msg, fileUrl, fileName}} = res
              let href = bootConfig[process.env.NODE_ENV].VUE_APP_API + fileUrl
              this.$warning({
                title: message,
                content: (
                  < div >
                    < span > {msg} < /span><br/ >
                    < span > { this.$t('m.eform.formDesign.label.ju-ti-xiang-qing-qing') } < a href = {href} target = '_blank' download = {fileName} > { this.$t('m.eform.formDesign.label.dian-ji-xia-zai') } < /a></span >
                  < /div>
                )
              })
            }else {
              this.messageUtil.success(res.message)
            }
          } else {
            this.messageUtil.warning(res.message)
          }
          this.selectedRowKeys = []
          this.selectionRows = []
          this.loadData()
        }).finally(() => {
          this.spinning--
        })
      }
    }
  }
</script>
<style lang="less" scoped>

</style>
